using System;
using System.Collections;
using System.Collections.Generic;
using Main.Event;
using UnityEngine;
using UnityEngine.Playables;
using ZSW.Framework;

namespace Main.Timeline
{
    public class TimelineManager : ZSWF_Singleton<TimelineManager>
    {
        public PlayableDirector starDirector;
        private PlayableDirector currentDirector;
        public bool IsDone;
        private bool isPause;
        public override void Init()
        {
            base.Init();

            currentDirector = starDirector;
        }

        private void OnEnable()
        {
            // currentDirector.played += TimeLinePlayed;
            // currentDirector.stopped += TimelineStopped;
            MainEventSystem.AfterLoadSceneEvent += OnAfterSceneLoad;
        }

        private void OnAfterSceneLoad()
        {
            currentDirector = FindObjectOfType<PlayableDirector>();

            currentDirector.Play();
        }

        private void TimelineStopped(PlayableDirector director)
        {
            if (director != null)
            {
                MainEventSystem.CallUpdateGameStateEvent(GameState.GamePlay);
                director.gameObject.SetActive(false);
            }
        }

        private void TimeLinePlayed(PlayableDirector director)
        {
            if (director != null)
            {
                MainEventSystem.CallUpdateGameStateEvent(GameState.Pause);
            }
        }

        private void Update()
        {
            if (isPause && Input.GetKeyDown(KeyCode.Space) && IsDone)
            {
                isPause = false;
                currentDirector.playableGraph.GetRootPlayable(0).SetSpeed(1d);
            }
        }

        public void PauseTimeLine(PlayableDirector director)
        {
            currentDirector = director;

            currentDirector.playableGraph.GetRootPlayable(0).SetSpeed(0d);

            isPause = true;
        }
    }

}
